package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author ljk74
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
@RequiredArgsConstructor
public class CommonController {
    private final AliOssUtil aliOssUtil;

    @ApiOperation("图片上传")
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.debug("文件上传：{}",file);
        try {
            //获得原始文件名
            String originalFilename = file.getOriginalFilename();
            //获取后缀
            String fileNameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //拼接新的文件名
            String newFileName = newFileName(fileNameSuffix);

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(),newFileName);
            return Result.success(filePath);
        }catch (IOException e){
            log.error("文件上传失败",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    private String newFileName(String suffix){
        String folderName = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM"));
        String fileName = UUID.randomUUID().toString() + suffix;
        return folderName+"/"+fileName;
    }
}
